﻿using ConfExpert.Forms.Base;
using ConfExpert.Forms.Rapor;

using DevExpress.Utils;
using DevExpress.XtraEditors;
using DevExpress.XtraGrid.Views.Grid;
using DevExpress.XtraReports.UI;
using DevTeam;


using System;
using System.Collections.Generic;
using System.Data;
using System.Drawing;
using System.Windows.Forms;

namespace ConfExpert.Forms.Depo.OverProduction
{
    public partial class OPOnayiniziBekleyen : XForm
    {
        public OPOnayiniziBekleyen()
        {
            InitializeComponent();
        }

        string tip;
        public OPOnayiniziBekleyen(string _tip)
            : this()
        {
            tip = _tip;
        }

        int Kim;
        BindingSource bsAyrim;
        private void OverProductions_Load(object sender, EventArgs e)
        {

            //WhoAmI = 1;
            GridManager gm;

            Kim = ytk(152) ? 1 :
                (ytk(153) ? 3 :
                2);

            switch (Kim)
            {
                case 1:     //Depo
                    gvOP.Init("GetOP2", Kim, WhoAmI, tip);

                    gvOP.SetCaptions(
                        "LastSeenQty:Son Bilinen Miktar"
                        , "RfidSet:RFID Yazıldı"
                        , "BarkodSet:Barkod Basıldı"
                        , "CikisTipiId:Çıkış Tipi"
                        );

                    gm = GridManager.GetManager(gvOP);
                    gm.GridMenu.AddMenu("Etiket Yazdır", EtiketBas);

                    break;

                case 3:    //Kumaş Dept.

                    bsAyrim = new BindingSource(ds, "Ayrim");
                    InitGridView(gvAyrim, bsAyrim);
                    gvAyrim.OptionsView.NewItemRowPosition = NewItemRowPosition.Bottom;

                    //Foreign Key Oluşturma
                    DataTable dtOP = ExecuteDataTable("GetOP2", Kim, WhoAmI, tip);
                    dtOP.TableName = "OPx";
                    ds.Tables.Add(dtOP);
                    ds.Relations.Add(new DataRelation("FK_Ayrim_OP_AyrimId", ds.Ayrim.AyrimIdColumn, dtOP.Columns["AyrimId"]));
                    dtOP.Columns.Add("BrandId", typeof(int), "Parent(FK_Ayrim_OP_AyrimId).BrandId");

                    gvOP.Init(dtOP);

                    gvOP.MakeReadOnly("StokGrupId");
                    gvOP.SetCaptions("LastSeenQty:Son Bilinen Miktar");

                    gm = GridManager.GetManager(gvOP);
                    gm.GridMenu.AddMenu("Seçili topları ayır", AyirR_Click);

                    gvAyrim.OptionsView.EnableAppearanceOddRow = gvAyrim.OptionsView.EnableAppearanceEvenRow = false;

                    gvAyrim.RowStyle += new RowStyleEventHandler(gvAyrim_RowStyle);
                    gvAyrim.RowCellStyle += new RowCellStyleEventHandler(gvAyrim_RowCellStyle);

                    //bsOP.Filter = "AyrimTarihi is null";
                    break;

                default:    //MTler+planlamacılar
                    gvOP.Init("GetOP2", Kim, WhoAmI, tip);

                    if (tip != "Tela")
                    {
                        gm = GridManager.GetManager(gvOP);
                        gm.GridMenu.AddMenu("Müşteri kullanacak", Kullanacak_Click);
                        gm.GridMenu.AddMenu("Müşteri kullanmayacak", Kullanmayacak_Click);
                    }
                    //bsOP.Filter = "KontrolTarihi is null AND AyrimTarihi is null";
                    break;

            }

            gvOP.RowCellStyle += new RowCellStyleEventHandler(gvOP_RowCellStyle);

            splitContainerControl1.AutoSize(0.65);

            //btnGuncelle.ItemClick += btnGuncelle_ItemClick;
            btnKaydet.ItemClick += btnKaydet_ItemClick;
            btnAyir.Click += new EventHandler(btnAyir_Click);

            btnKaydet.Visibility = Kim > 1 ? DevExpress.XtraBars.BarItemVisibility.Always : DevExpress.XtraBars.BarItemVisibility.Never;

            //bsOP = gvOP.Init("GetOP2", Kim, WhoAmI, tip);

            if (Kim < 3)
            {
                ExpandCollapse(splitContainerControl1, AcKapa.Collapse);
                gcAyrim.Visible = splitContainerControl1.Panel2.Visible = false;
            }

            //gv.AddDetailGrid(gvTop, "RollId");
            //gvTop.AddDetailGrid(gvTopDetail, "RollId");

            gvOP.SetCaptions(
                "GeriDonenRollId:Dönen Top Id"
                , "NewQty:Dönen Miktar"
                , "CikisTarihi:Çıkış Tarihi"
                , "CikilanAtelyeId:Çıkılan Atölye"
                , "CikilanCustomerId:Çıkılan Müşteri"
                , "CikilanVendorId:Çıkılan Üretici"
                , "CikilanOrderRef:Order Ref."
                , "CikilanBrandId:Marka"
                , "CikilanSezonId:Sezon"
                , "GirisTarihi:Giriş Tarihi"
                );

            gvOP.Columns["CikilanAtelyeId"].ColumnEdit = RI(Rp.Atelye);
            gvOP.Columns["CikilanCustomerId"].ColumnEdit = RI(Rp.V_Customer);
            gvOP.Columns["CikilanVendorId"].ColumnEdit = RI(Rp.Vendor);
            gvOP.Columns["CikilanBrandId"].ColumnEdit = RI(Rp.Brand);
            gvOP.Columns["CikilanSezonId"].ColumnEdit = RI(Rp.Sezon);
            gvOP.AddSummary("NewQty");


            if (tip == "Tela")    //Miwako,Tülay
            {


                this.Text = "OP Tela Topları";
                gvOP.AddSummary("LastSeenQty");
                gvOP.SetCaptions("LastSeenQty:Çıkan Miktar");
                gvOP.MakeColumnInvisible("CikilanVendorId", "AyrimTarihi", "AyrimId", "isTela");
                splitContainerControl1.PanelVisibility = SplitPanelVisibility.Panel1;
            }

            //gvOP.OptionsBehavior.Editable = false;
            gvOP.ShowingEditor += new System.ComponentModel.CancelEventHandler(gvOP_ShowingEditor);
            gvOP.BestFitColumns();

            gvAyrim.ShowingEditor += new System.ComponentModel.CancelEventHandler(gvAyrim_ShowingEditor);
            gvOP.MakeColumnInvisible("ProductId");
        }

        void btnKaydet_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            gvOP.EndEditing();

            switch (Kim)
            {
                case 2:    //MT
                    dt = new DataTable("Table");
                    dt.Columns.Add("RollId", typeof(int));
                    dt.Columns.Add("MusteriKullanacakMi", typeof(string));

                    foreach (DataRow dr in gvOP.Dataset().Tables[0].GetChanges().Rows)
                        dt.Rows.Add(intParse(dr["YeniRollId"]), dr["MusteriKullanacakMi"].ToString());

                    //foreach (int handle in gvOP.GetSelectedRows())
                    //    dt.Rows.Add(intParse(gvOP.GetRowCellValue(handle, "YeniRollId")),
                    //        gvOP.GetRowCellDisplayText(handle, "MusteriKullanacakMi"));

                    ExecuteNonQuery("UpdOP_Mt", dt.SerializeChanges(), WhoAmI);
                    gvOP.RefreshDataSource("GetOP2", Kim, WhoAmI, tip);
                    break;

                case 3:    //Kumaş Dept.
                    dt = new DataTable("Table");
                    dt.Columns.Add("RollId", typeof(int));
                    dt.Columns.Add("AyrimId", typeof(int));
                    dt.Columns.Add("StokGrupId", typeof(int));

                    foreach (DataRow dr in ds.Tables["OPx"].Select("AyrimId is not null"))
                    {
                        dt.Rows.Add(intParse(dr["YeniRollId"]), intParse(dr["AyrimId"]), intParse(dr["StokGrupId"]));
                        ds.Tables["OPx"].Rows.Remove(dr);
                    }

                    ExecuteNonQuery("UpdOP_KDept", dt.SerializeChanges(), WhoAmI);

                    break;
            }
        }

        void btnGuncelle_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            gvOP.EndEditing();
            DataTable dtOP = ExecuteDataTable("GetOP2", Kim, WhoAmI, tip);
            dtOP.TableName = "OPx";
            gvOP.RefreshDataSource(dtOP, true);
        }

        void gvOP_RowCellStyle(object sender, RowCellStyleEventArgs e)
        {
            switch (e.Column.FieldName)
            {
                case "NewQty":
                    e.Appearance.Font = new Font(AppearanceObject.DefaultFont, FontStyle.Bold);
                    break;
                default:
                    break;
            }

        }


        void GetBolunenTopIds()
        {
            if (gvOP.SelectedRowsCount < 1)
                gvOP.SelectRow(gvOP.FocusedRowHandle);

            TelaIds.Clear();
            KumasIds.Clear();

            foreach (int handle in gvOP.GetSelectedRows())
            {
                string rollId = gvOP.GetRowCellValue(handle, "YeniRollId").ToString();

                if (intParse(gvOP.GetDataRow(handle)["isTela"].ToString()) > 0)
                    TelaIds.Add(rollId);
                else
                    KumasIds.Add(rollId);
            }
        }

        List<string> KumasIds = new List<string>();
        List<string> TelaIds = new List<string>();
        private string GetKumasRolls()
        {
            return String.Join(",", KumasIds.ToArray());
        }

        private string GetTelaRolls()
        {
            return String.Join(",", TelaIds.ToArray());
        }

        void EtiketBas(object sender, EventArgs e)
        {
            GetBolunenTopIds();

            if (KumasIds.Count > 0)
            {
                TopEtiketleri2 barcode = new TopEtiketleri2(Enums.EtiketTipi.OP, GetKumasRolls());
                barcode.ShowDialog();
            }

            if (TelaIds.Count > 0)
            {
                Rapor.TelaBarkod telaBarcode = new Rapor.TelaBarkod(Enums.EtiketTipi.OP, GetTelaRolls());
                telaBarcode.ShowPreview();
            }
        }

        private void gvAyrim_ShowingEditor(object sender, System.ComponentModel.CancelEventArgs e)
        {
            //e.Cancel = intParse(bsAyrim, "AyrimId") > 0;
            e.Cancel = !(gvAyrim.FocusedRowHandle == DevExpress.XtraGrid.GridControl.NewItemRowHandle ||
                intParse(bsAyrim, "AyrimId") < 0);
        }

        void gvAyrim_RowCellStyle(object sender, RowCellStyleEventArgs e)
        {
            switch (e.Column.FieldName)
            {
                case "BrandId":
                    e.Appearance.Font = new Font(AppearanceObject.DefaultFont, FontStyle.Bold);
                    break;
                default:
                    break;
            }
        }

        void gvAyrim_RowStyle(object sender, RowStyleEventArgs e)
        {
            GridView view = sender as GridView;
            if (e.RowHandle > -1)
            {
                if (e.RowHandle == gvAyrim.FocusedRowHandle)
                    e.Appearance.BackColor = e.Appearance.BackColor2 = Color.YellowGreen;   // Color.FromArgb(255, 192, 0);
                else
                    e.Appearance.Combine((e.RowHandle & 1) != 0 ? view.Appearance.EvenRow : view.Appearance.OddRow);
            }
        }

        void btnAyir_Click(object sender, EventArgs e)
        {
            gvAyrim.EndEditing();
            //int frh = gvAyrim.FocusedRowHandle;

            int ayrimId = gvAyrim.GetFocusedRowCellValue("AyrimId").ToInt();
            DataSet d = ExecuteDataSet("UpdAyrimStokGiris2", ds.Ayrim.Serialize(), ayrimId);
            ds.Ayrim.Clear();
            ds.Ayrim.Merge(d.Tables[0]);

            int newAyrimId = d.Tables[1].Rows[0][0].ToInt();

            gvAyrim.FocusedRowHandle = gvAyrim.LocateByValue("AyrimId", newAyrimId);
            gvAyrim.BestFitColumns();
            //TAM.AyrimTableAdapter.Update(ds.Ayrim);
        }



        void AyirR_Click(object sender, EventArgs e)
        {
            //gvOP.CloseEditor();
            //gvOP.UpdateCurrentRow();

            btnAyir.PerformClick();
            int AyrimId = intParse(gvAyrim.GetFocusedRowCellValue("AyrimId"));
            if (AyrimId < 1)
                return;

            foreach (int handle in gvOP.GetSelectedRows())
                gvOP.SetRowCellValue(handle, "AyrimId", AyrimId);

            //gvOP.RefreshData();
        }

        DataTable dt;


        void gvOP_ShowingEditor(object sender, System.ComponentModel.CancelEventArgs e)
        {
            e.Cancel = gvOP.FocusedColumn.FieldName != "StokGrupId";
        }

        void Kullanacak_Click(object sender, EventArgs e)
        {
            gvOP.EndEditing();
            //List<string> r = new List<string>();
            foreach (int rowHandle in gvOP.GetSelectedRows())
                if (rowHandle > -1)
                {
                    //r.Add(gvOP.GetRowCellDisplayText(rowHandle, "YeniRollId"));
                    gvOP.SetRowCellValue(rowHandle, "MusteriKullanacakMi", "E");
                }
        }

        void Kullanmayacak_Click(object sender, EventArgs e)
        {
            gvOP.EndEditing();
            //List<string> r = new List<string>();
            foreach (int rowHandle in gvOP.GetSelectedRows())
                if (rowHandle > -1)
                {
                    //r.Add(gvOP.GetRowCellDisplayText(rowHandle, "YeniRollId"));
                    gvOP.SetRowCellValue(rowHandle, "MusteriKullanacakMi", "H");
                }
        }


    }
}